package com.proj.hot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.adapter.FragmentAdapter;
import com.proj.hot.fragment.RecFragment;
import com.proj.hot.fragment.askFragment;
import com.proj.hot.fragment.banFragment;
import com.proj.hot.fragment.chaFragment;
import com.proj.hot.login.DataManager;
import com.proj.hot.login.LoginResultCallBack;
import com.proj.hot.utils.BaseInfoUtil;
import com.proj.hot.utils.DebugUtil;
import com.proj.hot.utils.ImageLoaderConfigFactory;
import com.proj.hot.widget.CustomViewPager;
import com.proj.hot.widget.PagerScroller;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 主launch
 */
public class LaunchActivity extends BaseActivity {

    private final String TAG = getClass().getSimpleName();

    private FrameLayout mainFrameLayout;
    private String localBgUrl;
    private ImageView launchBg;

    private DigitalClock digitalClock;

    private Button btnRec, btnMovie, btnShopping, btnTravel, btnUserCenter;

    private RecFragment recFragment;//推荐
//    private MovieFragment movieFragment;//电影

//    private TravelFragment travelFragment;//旅游
//    private ShoppingFragment shoppingFragment;//电商
//    private UserCenterFragment userCenterFragment;//用户中心
    private banFragment banFragment;
    private chaFragment chaFragment0;
    private askFragment askFragment;//问

    public CustomViewPager viewPager;//viewpager
    private List<Fragment> fragmentsList;//fragmentlist
    private List<Activity> activityList;//activityliasr
    private List<Bitmap> bgBitmapList;//bitmaplist

    private FragmentAdapter fragmentAdapter;

    private List<Button> btnList;
    /**
     * 如果认证失败，就显示这个布局
     */
    private RelativeLayout loginFailLayout;

    private LinearLayout loginSuccessLayout;

    private LinearLayout launch_ll_btns;

    private TextView nettag_tv;
    /**
     * 认证结果标识
     * 000：成功
     * 999：失败
     */
    private String loginFlag = "000";
    private String message = "";
    /**
     * 用户是否开机直接登录标识
     */
    private String userLoginTag;

    JSONArray dataArray;
    private TextView loginfailTv;

    private TextView weatherTv;

    public int movieFocus;
    public ImageView movieFocusView;
    public TextView movieBlackView;


    private static final int PAGER_SCROLL_SPEED = 600;//viewPager滑动速度


    String apkFilepath;
    int fileSize, downLoadFileSize;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {//0 为登录认证
//                Log.i("networkzzz", "有网络发了广播...");
//                DebugUtil.toast(LaunchActivity.this,"网络正常！");
//                getAppInfo();//1.获取app的一些参数
//                getLogin();//2.重点是：进行登录认证

            } else if (msg.what == 1) {
                nettag_tv.setVisibility(View.GONE);
                launch_ll_btns.setVisibility(View.VISIBLE);
                initView();
                setOnListener();
                getWeather();

            } else if (msg.what == 2) {

                //检查版本升级
                getVer(LaunchActivity.this);

            } else if (msg.what == 20) {
                final File file = new File(apkFilepath);
                DebugUtil.i("update_apk", "apkFilepath=" + apkFilepath);
                if (file.exists()) {

                    DebugUtil.i("update_apk", "#安装命令" + "pm install -r " + apkFilepath);
                    try {
//                        Runtime.getRuntime().exec("chmod 777 " + apkFilepath);
//                        Runtime.getRuntime().exec("pm install -r " + apkFilepath);
                        Process process = Runtime.getRuntime().exec("chmod 777 " + apkFilepath);
                        Process process1 = Runtime.getRuntime().exec("pm install -r " + apkFilepath);
                        int value = process1.waitFor();
                        DebugUtil.i("update_apk", "value=" + value);
                        // boolean updataFlag = returnResult(value);
                        if (value == 0) {//如果成功将重启
                            System.exit(0);
                        }

                    } catch (SecurityException e1) {
                        DebugUtil.i("update_apk", "#安装命令异常1:" + "pm install -r " + apkFilepath + ",e1=" + e1);
                    } catch (Exception e) {
                        DebugUtil.i("update_apk", "#安装命令异常2:" + "pm install -r " + apkFilepath + ",e=" + e);
                    }


                    //下面的为非静默安装
//                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.setDataAndType(Uri.parse("file:/" + apkFilepath),"application/vnd.android.package-archive");
//                    LaunchActivity.this.startActivity(intent);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launch);

        //测试用
//        Intent intent = new Intent(LaunchActivity.this,MovieDetailActivity.class);
//        intent.putExtra("contentid","34");
//        startActivity(intent);

        launchBg = (ImageView) this.findViewById(R.id.launch_bg);
        mainFrameLayout = (FrameLayout) this.findViewById(R.id.launch_main_bg);
        launch_ll_btns = (LinearLayout) this.findViewById(R.id.launch_ll_btns);
        launch_ll_btns.setVisibility(View.INVISIBLE);
        ivNet1 = (ImageView) this.findViewById(R.id.launch_net1);
        nettag_tv = (TextView) this.findViewById(R.id.nettag_tv);

        //cm05和04要监听广播
        if (GlobalParams.DEVICE_TYPE.equals("CM04") || GlobalParams.DEVICE_TYPE.equals("CM05")) {
            IntentFilter filter = new IntentFilter(
                    ConnectivityManager.CONNECTIVITY_ACTION);
            netStateReceiverS = new NetStateReceiverS();
            registerReceiver(netStateReceiverS, filter);
            Log.i("networkzzz", "网络判断执行了cm0405...");
        } else {//cm01直接请求

            Log.i("networkzzz", "网络判断执行了cm01...");
            getAppInfo();//1.获取app的一些参数
            getLogin();//2.重点是：进行登录认证
        }





    }

//    private int compareImgUrl(String serverUrl, String localUrl) {
//        if (serverUrl.equals(localUrl)) {
//            return 0;//认证返回的图片地址 与本地存储的图片地址 一致
//        } else {
//            return 1;//不一致
//        }
//    }
//
//    private String getBackgroundFromLocal() {
//        DebugUtil.i("SharedPreferences", "获取本地的图片地址！");
//        SharedPreferences sp = getSharedPreferences("mainbg", Context.MODE_PRIVATE);
//        String url = sp.getString("backgroundurl", "");
//        if (null != url && !"".equals(url)) {
//            return url;
//        } else {
//            return "";
//        }
//    }
//
//    private void savaBackgroundToLocal(String url) {
//        DebugUtil.i("SharedPreferences", "保存新的图片地址！");
//        SharedPreferences mSharedPreferences = getSharedPreferences("mainbg", Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = mSharedPreferences.edit();
//        editor.putString("backgroundurl", url);
//        editor.commit();
//
//    }
//
//    private void clealBackgroundToLocal() {
//        DebugUtil.i("SharedPreferences", "清除旧的图片地址！");
//        SharedPreferences sp = getSharedPreferences("mainbg", Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = sp.edit();
//        editor.clear();
//        editor.commit();
//    }
//
//    private void downLoadBackground(String url) {
//
//
//    }

    /**
     * 开机认证
     */
    private void getLogin() {

        loginSuccessLayout = (LinearLayout) this.findViewById(R.id.launch_rl_loginSuccess);
        loginFailLayout = (RelativeLayout) this.findViewById(R.id.launch_rl_loginfail);
        loginfailTv = (TextView) this.findViewById(R.id.loginfail_tv);
        DataManager.getlogin(GlobalParams.MAC_ADDRESS, GlobalParams.SN, "", GlobalParams.DEVICE_TYPE, "1234567890", "", String.valueOf(GlobalParams.curAppVerionCode),
                new LoginResultCallBack() {

                    @Override
                    public void onResultCallBack(String result) {

                        DebugUtil.i("yyst_login", "laucher的认证结果=" + result);

                        DebugUtil.i("yyst_login", "GlobalParams.feeMode=" + GlobalParams.feeMode);
                        DebugUtil.i("yyst_login", "GlobalParams.terminalId=" + GlobalParams.feeMode);
                        DebugUtil.i("yyst_login", "loginFlag=" + loginFlag);
                        DebugUtil.i("yyst_login", "GlobalParams.loginMsg=" + GlobalParams.loginMsg);
                        DebugUtil.i("yyst_login", "GlobalParams.hotelAddrUrl=" + GlobalParams.hotelAddrUrl);
                        DebugUtil.i("yyst_login", "GlobalParams.hotellId=" + GlobalParams.hotellId);
                        DebugUtil.i("yyst_login", "GlobalParams.hotelImg=" + GlobalParams.hotelImg);

                        loginFlag = result;
                        if (loginFlag.equals("998")) {//认证失败
                            loginFailLayout.setVisibility(View.VISIBLE);
                            loginSuccessLayout.setVisibility(View.GONE);
                            loginFailLayout.bringToFront();
                            loginfailTv.setText(GlobalParams.loginMsg);
                            return;
                        } else if (loginFlag.equals("990")) {//认证失败
                            loginFailLayout.setVisibility(View.VISIBLE);
                            loginSuccessLayout.setVisibility(View.GONE);
                            loginFailLayout.bringToFront();
                            loginfailTv.setText(GlobalParams.loginMsg);
                            return;
                        } else {
                            if (GlobalParams.hotelImg.equals("")) {//如果认证返回的背景地址为空，加载默认背景
                                DebugUtil.i("SharedPreferences", "认证返回背景地址为空！");
                                launchBg.setBackgroundResource(R.drawable.home_bg);
                            } else {
                                ImageLoader.getInstance().clearMemoryCache();
                                ImageLoader.getInstance().clearDiskCache();
                                ImageLoader.getInstance().displayImage(GlobalParams.hotelImg,
                                        launchBg, ImageLoaderConfigFactory.getOptionsWithNopic());
                            }

                            loginSuccessLayout.setVisibility(View.VISIBLE);//认证成功
                            loginFailLayout.setVisibility(View.GONE);
                            loginSuccessLayout.bringToFront();
                            //认证成功后，酒店服务器地址
                            GlobalParams.reqHost = GlobalParams.hotelAddrUrl + "/";
                            DebugUtil.i("yyst_login", "屏幕宽：" + GlobalParams.screenWidth);
                            DebugUtil.i("yyst_login", "服务器地址：" + GlobalParams.reqHost);
//                            DebugUtil.toast(LaunchActivity.this, "认证返回来的内网地址：" + GlobalParams.reqHost);


                            //GlobalParams.hotelImg = "";

                            // DebugUtil.i("SharedPreferences", "localUrl=" + localBgUrl);
                            // DebugUtil.i("SharedPreferences", "serverUrl=" + GlobalParams.hotelImg);
//                    if (GlobalParams.hotelImg.equals("")) {//如果认证返回的背景地址为空，加载默认背景
//                        DebugUtil.i("SharedPreferences", "认证返回背景地址为空！");
//                        mainFrameLayout.setBackgroundResource(R.drawable.home_bg);
//                    } else {
//                        localBgUrl = getBackgroundFromLocal();
//                        DebugUtil.i("SharedPreferences", "本地图片地址:"+localBgUrl);
//                        DebugUtil.i("SharedPreferences", "网络图片地址:"+GlobalParams.hotelImg);
//                        if("".equals(localBgUrl)){
//                            savaBackgroundToLocal(GlobalParams.hotelImg);//如果本地没有地址，保存认证返回的地址
//                            DebugUtil.i("SharedPreferences", "一.本地没有地址，地址保存到本地");
//                            DebugUtil.i("SharedPreferences", "二.下载到本地");
//                            DebugUtil.i("SharedPreferences", "三.加载");
//
//                        }else{
//                            if(localBgUrl.equals(GlobalParams.hotelImg)){//如果本地和服务器返回地址一致
//                                //不下载，背景加载已经下载好路径的图片
//                                DebugUtil.i("SharedPreferences", "服务器上的图片和本地的一致，加载本地背景！");
//                            }else{
//                                //清除本地记录，保存新的地址，下载图片到指定路径
//                                DebugUtil.i("SharedPreferences", "服务器上的图片和本地的不一致，开始走流程！");
//                                DebugUtil.i("SharedPreferences", "1.清除本地图片地址！");
//                                DebugUtil.i("SharedPreferences", "2.保存网络图片地址到本地！");
//                                DebugUtil.i("SharedPreferences", "3.下载图片到本地路径！");
//                                DebugUtil.i("SharedPreferences", "4.下载完毕加载图片！");
//                            }
//
//                        }
//                    }


                            getRootDate();//3.获取数据
                            return;
                        }
                    }

                    @Override
                    public void onErrorCallBack(String errorInfo) {
                        DebugUtil.toast(LaunchActivity.this, errorInfo);
                        launchBg.setBackgroundResource(R.drawable.home_bg);
                        loginFailLayout.setVisibility(View.GONE);
                        loginSuccessLayout.setVisibility(View.VISIBLE);
                        loginFailLayout.bringToFront();

                        getRootDate();

                    }
                }

        );

        //检查版本升级
        handler.sendEmptyMessageDelayed(2, 5000);

    }

    /**
     * 获取根数据
     */
    private void getRootDate() {

        try {


            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("hotelcode", GlobalParams.hotellId);


            RequestParams params = new RequestParams(GlobalParams.reqHost + "featuredFirst/getRootFirst");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    if (!"".equals(s) || null != s) {
                        if (GlobalParams.DEVICE_TYPE.equals("CM04") || GlobalParams.DEVICE_TYPE.equals("CM05")) {
                            if(netStateReceiverS!=null) {
                                unregisterReceiver(netStateReceiverS);
                                Log.i("networkzzz", "注销了网络判断的广播");
                            }
                        }
                    }

                    try {
                        JSONObject jData = new JSONObject(s);

                        JSONObject respbody = jData.getJSONObject("respbody");
                        dataArray = respbody.getJSONArray("data");
                        handler.sendEmptyMessage(1);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 获取天气
     */
    private void getWeather() {

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("hotelcode", GlobalParams.hotellId);


            RequestParams params = new RequestParams(GlobalParams.reqHost + "weather/getWeatherBySn");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        JSONObject jData = new JSONObject(s);

                        JSONObject respbody = jData.getJSONObject("respbody").getJSONObject("data");
                        weatherTv = (TextView) LaunchActivity.this.findViewById(R.id.tv_weather);
                        if (GlobalParams.screenHeight == 1080) {//1920*1080 dpi=160
                            weatherTv.setTextSize(23);
                        }

//                        "date": "12日星期六",
//                                "high": "高温 35℃",
//                                "low": "低温 28℃",
//                                "city": "广州",
//                                "fengxiang": "无持续风向",
//                                "type": "多云"

                        String city = respbody.getString("city");
                        String date = respbody.getString("date");
                        String high = respbody.getString("high");
                        String low = respbody.getString("low");
                        String type = respbody.getString("type");
                        weatherTv.setText(city + "   " + low + "~" + high + "   " + type);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void initView() {
        digitalClock = (DigitalClock) this.findViewById(R.id.dclock);
        movieFocusView = (ImageView) this.findViewById(R.id.launcg_movie_focus_boder);
        if (GlobalParams.screenHeight == 672) {//1280*672 dpi=
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) movieFocusView
                    .getLayoutParams();
            lp.height = 413;
            lp.setMargins(0, 0, 0, 38);
            movieFocusView.setLayoutParams(lp);
            movieFocusView.setLayoutParams(lp);
        }
        if (GlobalParams.screenHeight == 720) {//1280*720 dpi=160
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) movieFocusView
                    .getLayoutParams();
            lp.height = 412;
            lp.setMargins(0, 0, 0, 40);
            movieFocusView.setLayoutParams(lp);
            movieFocusView.setLayoutParams(lp);
        }
        if (GlobalParams.screenHeight == 1080) {//1920*1080 dpi=160
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) movieFocusView
                    .getLayoutParams();
            lp.height = 618;
            lp.setMargins(0, 0, 0, 34);
            movieFocusView.setLayoutParams(lp);
            movieFocusView.setLayoutParams(lp);

            digitalClock.setTextSize(25);

//            FrameLayout.LayoutParams lp1 = (FrameLayout.LayoutParams) digitalClock
//                    .getLayoutParams();
//            lp.height = 618;
//            digitalClock.setLayoutParams(lp1);
//            digitalClock.setLayoutParams(lp1);
        }
        movieBlackView = (TextView) this.findViewById(R.id.launcg_movie_focus_black);
        btnRec = (Button) this.findViewById(R.id.launch_btn1);
        btnMovie = (Button) this.findViewById(R.id.launch_btn2);
        btnTravel = (Button) this.findViewById(R.id.launch_btn4);
        btnShopping = (Button) this.findViewById(R.id.launch_btn3);
        btnUserCenter = (Button) this.findViewById(R.id.launch_btn5);
        btnList = new ArrayList<>();
        btnList.add(btnRec);
        btnList.add(btnMovie);
        btnList.add(btnTravel);
        btnList.add(btnShopping);
        btnList.add(btnUserCenter);
        try {

            viewPager = (CustomViewPager) this.findViewById(R.id.viewpager);

            recFragment = new RecFragment();
            recFragment.setCodeAndInitData(dataArray.getJSONObject(0).getString("code"));
            btnRec.setText("");


            banFragment = new banFragment();
            banFragment.setCodeAndInitData(dataArray.getJSONObject(1).getString("code"));
            btnMovie.setText("");


            chaFragment0 = new chaFragment();
            chaFragment0.setCodeAndInitData(dataArray.getJSONObject(2).getString("code"));
            btnShopping.setText("");


//            banFragment = new banFragment();
//            banFragment.setCodeAndInitData(dataArray.getJSONObject(3).getString("code"));
//            btnTravel.setText(dataArray.getJSONObject(3).getString("name"));





            askFragment = new askFragment();

        } catch (JSONException e) {
            e.printStackTrace();
        }


        fragmentsList = new ArrayList<>();
        fragmentsList.add(recFragment);
        fragmentsList.add(banFragment);

//        fragmentsList.add(banFragment);
        fragmentsList.add(chaFragment0);
        fragmentsList.add(askFragment);

        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentsList);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.setOffscreenPageLimit(5);
        viewPager.setCurrentItem(0);
        setViewPagerScrollSpeed(PAGER_SCROLL_SPEED);

    }


    private void setOnListener() {
        btnRec.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    viewPager.setCurrentItem(0);
                    recFragment.isOnShow(0);
                    movieFocus = 0;
                    GlobalParams.viewpageCur = 0;
                }
            }
        });
        btnMovie.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    viewPager.setCurrentItem(1);
                    recFragment.isOnShow(1);
                    movieFocus = 1;
                    movieFocusView.setVisibility(View.GONE);
                    // movieBlackView.setVisibility(View.VISIBLE);
                    GlobalParams.galleryFocus = 1;
                    GlobalParams.viewpageCur = 1;
                }
            }
        });
//        btnMovie.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View view, int i, KeyEvent keyEvent) {
//                if (i == KeyEvent.KEYCODE_DPAD_UP && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
//                    movieFocusView.setVisibility(View.VISIBLE);
//                    // movieBlackView.setVisibility(View.VISIBLE);
//                    movieFocusView.bringToFront();
//                }
//                return false;
//            }
//        });
        btnShopping.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    viewPager.setCurrentItem(2);
                    recFragment.isOnShow(2);
                    movieFocus = 0;
                    movieFocusView.setVisibility(View.GONE);
                    // movieBlackView.setVisibility(View.GONE);
                    GlobalParams.viewpageCur = 1;
                }
            }
        });
        btnTravel.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    viewPager.setCurrentItem(3);
                    recFragment.isOnShow(3);
                    movieFocus = 0;
                    movieFocusView.setVisibility(View.GONE);
                    // movieBlackView.setVisibility(View.GONE);
                    GlobalParams.viewpageCur = 1;
                }
            }
        });
        btnUserCenter.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    viewPager.setCurrentItem(4);
                    recFragment.isOnShow(4);
                    movieFocus = 0;
                    movieFocusView.setVisibility(View.GONE);
                    // movieBlackView.setVisibility(View.GONE);
                    GlobalParams.viewpageCur = 1;
                }
            }
        });

    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if(GlobalParams.DEVICE_TYPE.equals("CM04")||GlobalParams.DEVICE_TYPE.equals("CM05")) {
//            unregisterReceiver(netStateReceiverS);
//        }
//    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        Log.i("networkzzz","键值="+keyCode);
//        if(keyCode==82){
//            showPassWordDialog();
//            return false;
//        }
//        if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            return false;
//        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if (GlobalParams.galleryFocus == GlobalParams.galleryListSize) {
//                return true;
//            }
//            return false;
//        } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if (GlobalParams.galleryFocus == 0) {
//                return true;
//            }
//            return false;
//        } else if (keyCode == KeyEvent.KEYCODE_BACK
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            return false;
//        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if (movieFocus == 1) {
//                DebugUtil.i("focustest", "从电影页按了下");
//                btnMovie.requestFocus();
//                movieFocusView.setVisibility(View.GONE);
//            }
//            return false;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /**
     * 获取app一些基本信息
     */
    private void getAppInfo() {
        GlobalParams.screenWidth = BaseInfoUtil.getWindowsWidth(this);//屏幕宽度
        GlobalParams.screenHeight = BaseInfoUtil.getWindowsHeight(this);//屏幕高度
        GlobalParams.screenDPI = BaseInfoUtil.getWindowsDPI(this);//屏幕密度/ 720-160、1080-240、4K-320
        GlobalParams.MAC_ADDRESS = BaseInfoUtil.getMacAddress();//mac
        GlobalParams.IP_ADDRESS = BaseInfoUtil.getIPAddress();//ip
        GlobalParams.curAppVerionCode = BaseInfoUtil.getVersionCode(this);//版本号
        GlobalParams.curAppVerionName = BaseInfoUtil.getVersionName(this);//版本名
        DebugUtil.i(TAG, "屏幕宽度=" + GlobalParams.screenWidth);
        DebugUtil.i(TAG, "屏幕高度=" + GlobalParams.screenHeight);
        DebugUtil.i(TAG, "屏幕密度=" + GlobalParams.screenDPI);
        DebugUtil.i(TAG, "mac地址=" + GlobalParams.MAC_ADDRESS);
        DebugUtil.i(TAG, "ip地址=" + GlobalParams.IP_ADDRESS);
        DebugUtil.i(TAG, "VersionCode=" + GlobalParams.curAppVerionCode);
        DebugUtil.i(TAG, "VesionName=" + GlobalParams.curAppVerionName);
        //DebugUtil.toast(this, "版本号:" + GlobalParams.curAppVerionCode + ",设备型号：" + GlobalParams.DEVICE_TYPE);
        if (!GlobalParams.MAC_ADDRESS.equals("")) {
            GlobalParams.SN = GlobalParams.MAC_ADDRESS;
        } else {
            GlobalParams.SN = "";
        }
        DebugUtil.i(TAG, "SN=" + GlobalParams.SN);


        //测试
        GlobalParams.MAC_ADDRESS = "aa:bb:cc:11:22:33";
        GlobalParams.SN = "xyz";
    }

    /**
     * ViewPager的滑动速度
     *
     * @param duration
     */
    PagerScroller mScroller;

    private void setViewPagerScrollSpeed(int duration) {
        try {
            Field mField;
            mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);
            mScroller = new PagerScroller(this, new DecelerateInterpolator());
            mScroller.setmDuration(duration);
            mField.set(viewPager, mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ==========================以下为网络状态监听==================================
     */

    /**
     * 是否有网络
     */
    /**
     * 网络状态的图标
     */
    private ImageView ivNet1;
    /**
     * 监听网络状态改变的广播
     */
    private NetStateReceiverS netStateReceiverS;
    private boolean hasNetwork = true;
    private int netFlag = -1;
    private final static int MSG_CHECKING = 1;
    private static int CHECKING_COUNT = 0;
    private boolean bbbbb = true;
    Handler NetworkMoniter = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case MSG_CHECKING: {
                    if (isNetWorkConnected()) {
                        //如果有网络
                        nettag_tv.setText("正在初始化数据，请稍后...");
                        CHECKING_COUNT = 0;
                        DebugUtil.i("networkzzz", "有网络！");
                        //DebugUtil.toast(LaunchActivity.this,"网络正常！");
                        //DebugUtil.toast(LaunchActivity.this,"有网络！");
                        getAppInfo();
                        getLogin();
                        NetworkMoniter.removeMessages(MSG_CHECKING);// 如果有网络连接，remove

                    } else {

                        if (CHECKING_COUNT > 15)// 15s TimeOut
                        {
                            if (bbbbb) {
                                try {
                                    DebugUtil.i(TAG, "没有网络！");
                                    DebugUtil.toast(LaunchActivity.this, "没有网络，请进行网络设置!");
                                    Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                    startActivity(intent);
                                    NetworkMoniter.removeMessages(MSG_CHECKING);

                                }catch (Exception e){
                                    DebugUtil.toast(LaunchActivity.this,"拉起设置出现异常！");
                                }

                            }
                            bbbbb = false;
                            nettag_tv.setText("正在进行网络连接，请稍后...");
                        }
                        CHECKING_COUNT++;
                        SendNetworkCheckMsg(MSG_CHECKING, 1000);
                    }

                    break;

                }

            }
        }
    };


    class NetStateReceiverS extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            ConnectivityManager connectivityManager = (ConnectivityManager) arg0
                    .getSystemService(arg0.CONNECTIVITY_SERVICE);
            hasNetwork = connectivityManager.getActiveNetworkInfo() != null;
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null) {
                if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    netFlag = 0;// 0 为此网络类型是WIFI
                } else {
                    netFlag = 1;// 1 为非WIFI网络
                }
            }
            if (!hasNetwork) {
                ivNet1.setImageResource(R.drawable.launch_intent_offline);
                //ivNet.setImageResource(R.drawable.launch_intent_offline);
                //SendNetworkCheckMsg(0, 1000);
            } else {
                if (netFlag == 0) {
                    ivNet1.setImageResource(R.drawable.launch_wifi_full);
                } else if (netFlag == 1) {
                    ivNet1.setImageResource(R.drawable.launch_intent_online);
                }
                Log.i("networkzzz","执行了网络广播里面的函数");
                SendNetworkCheckMsg(0, 1000);
            }

        }

    }

    private void SendNetworkCheckMsg(int Msg, long delay) {
        Message m = new Message();
        m.arg1 = MSG_CHECKING;
        m.what = Msg;
        NetworkMoniter.removeMessages(m.what);
        NetworkMoniter.sendMessageDelayed(m, delay);
    }

    private boolean isNetWorkConnected() {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (activeNetInfo != null) {
                if ((activeNetInfo.getState() == NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        } catch (Exception e) {

        }

        return false;
    }


    void getVer(final Context context) {

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);

            RequestParams params = new RequestParams(GlobalParams.reqHost + "attestation/getAppUpgrade");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        DebugUtil.i("update_apk", "服务器返回的升级数据:" + s);
                        JSONObject jData = new JSONObject(s);

                        JSONObject respbody = jData.getJSONObject("respbody");
                        JSONObject data = respbody.getJSONObject("data");
                        if (data != null) {

                            int ver = data.getInt("verison");
                            PackageManager manager = context.getPackageManager();
                            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                            int version = info.versionCode;

                            if (ver > version) {
                                Toast.makeText(context, "正在准备版本升级更新，更新完毕之后自动重启！", Toast.LENGTH_SHORT).show();
                                String apkurl = data.getString("path");
                                loadData(apkurl);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    void loadData(final String mApkurl) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                try {
                    downLoadFile(mApkurl);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    }


    //下载apk程序代码
    protected File downLoadFile(String httpUrl) throws MalformedURLException {
        // TODO Auto-generated method stub final String fileName = "updata.apk";

        // 下载函数
        String filename = httpUrl.substring(httpUrl.lastIndexOf("/") + 1);
//        String dic= mContext.getFilesDir().getAbsolutePath();
        String dic = LaunchActivity.this.getExternalCacheDir().getAbsolutePath();

        File tmpFile = new File(dic);
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File(dic + "/" + filename);
        if (file.exists()) {
            file.delete();
        }


        apkFilepath = dic + "/" + filename;
        try {
            URL url = new URL(httpUrl);
            try {
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                InputStream is = conn.getInputStream();
                this.fileSize = conn.getContentLength();// 根据响应获取文件大小
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[256];
                conn.connect();
                downLoadFileSize = 0;
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);  //在这里使用另一个重载，防止流写入的问题.
                    downLoadFileSize += len;
                    ;
                }

                conn.disconnect();
                fos.close();
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();


                //  53002
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        handler.sendEmptyMessageDelayed(20, 1000);
        return file;
    }

//    private boolean returnResult(int value) {
//        // 代表成功
//        if (value == 0) {
//            DebugUtil.i("update_apk", "value=" + value);
//            return true;
//        } else if (value == 1) { // 失败
//            DebugUtil.i("update_apk", "value=" + value);
//            return false;
//        } else { // 未知情况
//            DebugUtil.i("update_apk", "value=" + value);
//            return false;
//        }
//    }

    private void showPassWordDialog() {

        final EditText et = new EditText(LaunchActivity.this);
        et.setSingleLine();
        new AlertDialog.Builder(LaunchActivity.this).
                setTitle("进入系统设置，请输入密码").
                setIcon(android.R.drawable.ic_dialog_info).
                setView(et).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String input = et.getText().toString().trim();
                        if (input.equals("")) {
                            DebugUtil.toast(LaunchActivity.this, "密码不能为空!");
                            return;
                        }
                        if (input.equals(GlobalParams.SYSTEM_SETTING_PASSWORD)) {
                            Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                            startActivity(intent);
                        } else {
                            DebugUtil.toast(LaunchActivity.this, "密码错误!");
                        }
                    }
                })
                .setNegativeButton("取消", null).show();
    }
}
